package com.liuceng.zen.web.controller;

import com.liuceng.zen.constants.Constants;
import com.liuceng.zen.pojo.domain.Application;
import com.liuceng.zen.pojo.domain.Member;
import com.liuceng.zen.pojo.domain.WechatUser;
import com.liuceng.zen.pojo.form.LoginForm;
import com.liuceng.zen.service.AccountService;
import com.liuceng.zen.service.ApplicationService;
import com.liuceng.zen.service.MemberService;
import com.liuceng.zen.service.WechatBindService;
import com.liuceng.zen.web.auth.HttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author liyuhang
 */
@Controller
public class SessionController extends BaseController {
    @Value("${appid}")
    private String appid;
    @Value("${wechat.redirect.url}")
    private String redirectUrl;
    @Autowired
    AccountService accountService;
    @Autowired
    WechatBindService wechatBindService;
    @Autowired
    MemberService memberService;
    @Autowired
    ApplicationService applicationService;

  // ----登录相关逻辑
  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String signIn(@ModelAttribute("form") LoginForm form, HttpServletRequest request) {
    // 若已经登录则直接跳转到管理首页
    if (getUserContext() != null && getCurrentUserId() != null) {
      return "redirect:/dashboard";
    }
    request.setAttribute("appid",appid);
    request.setAttribute("redirectUrl",redirectUrl);
    return "login";
  }

  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public String doSignIn(@Valid @ModelAttribute("form") LoginForm form, HttpServletRequest request,
      RedirectAttributes redirectAttributes) {
    if (getUserContext() != null && getCurrentUserId() != null) {
      redirectAttributes.addFlashAttribute(Constants.OK_MSG, "登录成功");
      return "redirect:/dashboard";
    }

    return signIn(form,request);
  }

  @RequestMapping(value = "/thirdparty_login", method = RequestMethod.POST)
  public String thirdpartySignIn() {
    return "";
  }

  @RequestMapping(value = "/landingpage/list", method = RequestMethod.GET)
  public String landingPage() {
    return "landingpage/list";
  }

  @RequestMapping(value = "/landingpage/add", method = RequestMethod.GET)
  public String landingPageAdd() {
    return "landingpage/add";
  }

  @RequestMapping(value = "/landingForms/list", method = RequestMethod.GET)
  public String landingPageLandform() {
    return "landingForms/list";
  }

  @RequestMapping(value = "/landingForms/add", method = RequestMethod.GET)
  public String landingPageLandformAdd() {
    return "landingForms/add";
  }

  /**
   * @param code  微信开放平台重定向这里，携带的code码
   * @param state 来自PC端还是Mobile端
   *
   * @author simon
   * @date 2016/02/24
   */
  @RequestMapping(value = "/wxlogin", method = RequestMethod.GET)
  public void wxlogin(String code, String state, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (!StringUtils.isEmpty(code)) {
      //1.根据code请求userinfo
      Map<String, Object> userinfoMap = wechatBindService.getUserInfoMap(code);
      //2.根据state判断是个人中心的微信号绑定，还是用户扫码登录
      String[] data = state.split("-");
      if ("2".equals(data[0])) {
          List<WechatUser> wechatUsers = wechatBindService.getBindedWechat(Integer.valueOf(data[1]));
          if(wechatUsers.size()<5){
            Integer isBinding = wechatBindService.saveWeChatUserMessage(userinfoMap,Integer.valueOf(data[1]));
            //重定向到个人中心页面
              request.getSession().setAttribute("isBinding",isBinding);
            response.sendRedirect("/profile");
          }else{
            //重定向到个人中心页面
              request.getSession().setAttribute("account",wechatUsers.size());
            response.sendRedirect("/profile");
          }
      } else if("1".equals(data[0])){
          //当前为登陆操作,去绑定表查询该微信号是否已经绑定过
          Member member = memberService.selectByWeChat(userinfoMap.get("unionid").toString(),null);
          if (member != null) {
              //用户已经绑定过
              HttpClient http=new HttpClient (response);
              http.setParameter("loginName",member.getUsername());
              http.setParameter("isWeChatLogin","true");
              http.sendByPost("/login");
          } else {
//              //用户第一次绑定,先去绑定手机号,先把userinfoMap放入session中
//              request.getSession().setAttribute("userinfoMap", userinfoMap);
              //重定向到注册申请页面
              response.sendRedirect("/apply");
          }
      }
    }
  }

    /**
     * 获取申请账号页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/apply", method = RequestMethod.GET)
    public String apply(HttpServletRequest request, HttpServletResponse response){
        return "/register";
    }

    /**
     * 保存申请账号表单
     * @param form
     * @return
     */
    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    public String doApply(@ModelAttribute("form") Application form){
        applicationService.addApplication(form);
        return "redirect:/apply/success";
    }

    @RequestMapping(value = "/ajax/member/check_company_name", method = RequestMethod.GET)
    @ResponseBody
    public Boolean checkCompanyNameForMember(String companyName){
        Boolean memberCompany = memberService.companyNameExists(null,companyName);
        Boolean applyCompany = applicationService.companyNameExists(companyName);
        return !memberCompany&&!applyCompany;
    }

    @RequestMapping(value = "/apply/success", method = RequestMethod.GET)
    public String applySuccess(HttpServletRequest request, HttpServletResponse response){
        return "/register_success";
    }
}
